from flask import render_template, g, current_app, abort, request, jsonify

from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.response_code import RET
from info.utils.common import user_login_data
from . import news_blu


@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    """新闻详情页"""
    news = None  # type:News

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)
    news.clicks += 1

    # 获取点击排行数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_click_list = []

    for news_ in news_list if news_list else []:
        news_click_list.append(news_.to_basic_dict())

    # 获取新闻评论
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = []
    user = g.user

    # 标记当前用户是否关注过当前新闻作者
    is_followed = False
    # 标记当前用户是否收藏过当前新闻
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

        if news.user_id:
            if user in news.user.followers:
                is_followed = True

        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 获取当前新闻的所有评论点赞记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == user.id).all()
                # 获取记录中所有评论的id
                comment_like_ids = [commentlike.comment_id for commentlike in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in comment_like_ids:
            comment_dict['is_like'] = True
        comment_list.append(comment_dict)



    data = {
        'user_info': g.user.to_dict() if g.user else None,
        'news': news.to_dict(),
        'news_click_list': news_click_list,
        'is_collected': is_collected,
        'is_followed':is_followed,
        'comment_list': comment_list
    }
    return render_template('news/detail.html', data=data)


@news_blu.route("/news_collect", methods=['POST'])
@user_login_data
def news_collect():
    """新闻收藏"""
    # 获取参数
    param_dict = request.json
    news_id = param_dict.get('news_id')
    action = param_dict.get('action')
    # 校验参数
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻数据不存在')

    if action == 'collect':
        g.user.collection_news.append(news)

    if action == 'cancel_collect':
        g.user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库保存失败')

    return jsonify(errno=RET.OK, errmsg='OK')


@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def add_news_comment():
    """添加新评论"""
    params_dict = request.json
    news_id = params_dict.get('news_id')
    comment = params_dict.get('comment')
    parent_id = params_dict.get('parent_id')

    if not all([news_id, comment]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')

    comments = Comment()
    comments.user_id = user.id
    comments.news_id = news_id
    comments.content = comment

    if parent_id:
        comments.parent_id = parent_id

    try:
        db.session.add(comments)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库提交失败')

    return jsonify(errno=RET.OK, errmsg='OK', data=comments.to_dict())


@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    """评论点赞"""

    # 获取参数
    params_dict = request.json
    comment_id = params_dict.get('comment_id')
    news_id = params_dict.get('news_id')
    action = params_dict.get('action')

    # 校验参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    if action not in ('add', 'remove'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='新闻评论不存在')

    comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                  CommentLike.user_id == user.id).first()
    if action == 'add':
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id
            db.session.add(comment_like_model)
            # 增加点赞条数
            comment.like_count += 1

    else:
        if comment_like_model:
            db.session.delete(comment_like_model)
            # 减少点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库提交失败')

    return jsonify(errno=RET.OK, errmsg='OK')


@news_blu.route('/followed_user', methods=['POSt'])
@user_login_data
def followed_user():
    """关注与取消关注"""
    # 要被关注用户的id
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    user_id = request.json.get('user_id')
    action = request.json.get('action')
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ('follow', 'unfollow'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        to_follow_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询错误')

    if not to_follow_user:
        return jsonify(errno=RET.NODATA, errmsg='你要关注的用户不存在')

    if action == 'follow':
        if user in to_follow_user.followers:
            return jsonify(errno=RET.DATAEXIST, errmsg='你已经关注过该用户')
        to_follow_user.followers.append(user)
    else:
        if user in to_follow_user.followers:
            to_follow_user.followers.remove(user)

    return jsonify(errno=RET.OK, errmsg='OK')

